package com.zd.kids.ui.activity;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.BarProperties;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OnBarListener;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.activity.BaseActivity;
import com.zd.kids.DataBean.PicBookDataBean;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.net.CustomApi;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.fragment.PicBookFragment;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


public class PicBookActivity extends BaseActivity {


    @BindView(R.id.view_statusbar)
    View viewStatusbar;
    @BindView(R.id.view_pager)
    ViewPager2 viewPager;
    @BindView(R.id.img_content)
    ImageView imgContent;
    @BindView(R.id.rl_cover)
    RelativeLayout rlCover;

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_pic_book;
    }

    String unitId;

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        ImmersionBar.with(PicBookActivity.this).hideBar(BarHide.FLAG_HIDE_BAR)
                .init();
        initPage2();

        Observable.timer(500, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        ImmersionBar.with(PicBookActivity.this).hideBar(BarHide.FLAG_HIDE_BAR)
                                .init();
                    }
                });

        unitId = getIntent().getStringExtra(TrainTypeListActivity.UNIT_ID_KEY);

        getPicBook();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }

    private void getPicBook() {
        showLoading();
        HttpMethod.getIntence().getPicBook(unitId, new CustomObserver<PicBookDataBean>(this) {
            @Override
            public void onSuccess(PicBookDataBean picBookDataBean) {
                disLoading();
                datas.clear();
                itemDatas = picBookDataBean.getResult();

                GlideUtil.loadfitCenter(picBookDataBean.getCover_img(), imgContent);
                downFiles(itemDatas);

            }

            @Override
            public void onError(String errorCode) {
                disLoading();
                finish();
            }
        });
    }

    List<PicBookDataBean.ResultBean> itemDatas;

    @OnClick({R.id.img_start, R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.img_start:
                isShowBookContent = true;
                if (isCompleteLoadBookContent) {
                    showBookContent(itemDatas);
                } else {
                    showLoading();
                }
                break;
        }
    }

    class FragmentAdapter extends FragmentStateAdapter {

        private List<Fragment> mDatas;

        public FragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> mDatas) {
            super(fragmentActivity);
            this.mDatas = mDatas;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return mDatas.get(position);
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }
    }


    private List<Fragment> datas;

    private FragmentAdapter mFragmentAdapter;

    private void initPage2() {
        datas = new ArrayList<>();
        mFragmentAdapter = new FragmentAdapter(this, datas);
        viewPager.setAdapter(mFragmentAdapter);

    }

    public void leftContent() {
        if (viewPager.getCurrentItem() != 0) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
        }
    }

    public void nextContent() {
        if (viewPager.getCurrentItem() != itemDatas.size() - 1) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
        }
    }

    public void startContent() {
        viewPager.setCurrentItem(0, false);
    }


    private void downFiles(List<PicBookDataBean.ResultBean> itemDatas) {

        Observable<String>[] observables = new Observable[itemDatas.size()];

        for (int i = 0; i < itemDatas.size(); i++) {
            PicBookDataBean.ResultBean resultBean = itemDatas.get(i);

            String audioPath = resultBean.getAudio_path();

            String fileName = audioPath.substring(audioPath.lastIndexOf("/"));

            observables[i] = getAudioFile(audioPath, fileName);
        }
        Observable.mergeArrayDelayError(observables)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String responseBody) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        disLoading();
                    }

                    @Override
                    public void onComplete() {
                        disLoading();
                        isCompleteLoadBookContent = true;
                        if (isShowBookContent) {
                            showBookContent(itemDatas);
                        }
                    }
                });
    }


    private boolean isShowBookContent;

    private boolean isCompleteLoadBookContent;

    private void showBookContent(List<PicBookDataBean.ResultBean> itemDatas) {
        rlCover.setVisibility(View.GONE);
        if (itemDatas != null) {
            for (int i = 0; i < itemDatas.size(); i++) {
                PicBookDataBean.ResultBean resultBean = itemDatas.get(i);

                PicBookFragment fragment = new PicBookFragment(resultBean);
                fragment.setUnitId(unitId);
                if (i == itemDatas.size() - 1) {
                    fragment.setLast(true);
                }
                datas.add(fragment);
            }
            mFragmentAdapter.notifyDataSetChanged();
        }
    }


    private Observable<String> getAudioFile(String urlPath, String fileName) {

        if (FileUtils.isFile(Constants.AUDIO_ROOT_PATH + fileName)) {
            return Observable.just(fileName);
        }

        return CustomApi.getIntence().getApi()
                .downFile(urlPath)
                .flatMap(new Function<ResponseBody, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(ResponseBody responseBody) throws Exception {
                        InputStream is = responseBody.byteStream();

                        String fileAbsolutePath = Constants.AUDIO_ROOT_PATH + fileName;

                        boolean isFile = FileIOUtils.writeFileFromIS(fileAbsolutePath, is);

                        if (isFile) {
                            return Observable.just(fileAbsolutePath);
                        } else {
                            return Observable.just("");
                        }
                    }
                });
    }

}